//
//  ForgotPasswordVC.m
//  优学荟管理系统
//
//  Created by 星道 on 17/9/4.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "ForgotPasswordVC.h"
#import "LLTools.h"

@interface ForgotPasswordVC ()
{
    IBOutlet UIScrollView *_scrollView;
    IBOutlet UIView *_surePwdView;
    IBOutlet NSLayoutConstraint *_scrollViewWidth;
    IBOutlet NSLayoutConstraint *_surePasswordTop;
    IBOutlet NSLayoutConstraint *_sureTop;
    IBOutlet UITextField *_phone;
    IBOutlet UITextField *_verification;
    IBOutlet UIButton *_verificationBtn;
    IBOutlet UIButton *_next;
    IBOutlet UITextField *_password;
    IBOutlet UITextField *_surePassword;
    IBOutlet UIButton *_commit;
    NSNumber *_uid;
    NSInteger _time;
}
@end

@implementation ForgotPasswordVC


#pragma mark - 生命周期
- (void)viewDidLoad {

    [super viewDidLoad];

    self.title = @"找回密码";

    _scrollViewWidth.constant = SCREEN_WIDTH * 2;

    // 设置不同选中状态的样式
    [self ButtonSelectStatus:_verificationBtn imageName:@"btn_next_default"];
    [self ButtonSelectStatus:_next imageName:@"btn_next_default"];
    [self ButtonSelectStatus:_commit imageName:@"btn_next_default"];
}





#pragma mark - 方法
/** 设置按钮的状态 */
- (void)ButtonSelectStatus:(UIButton *)button imageName:(NSString *)imageName {

    [button setBackgroundImage:[UIImage imageNamed:imageName] forState:(UIControlStateNormal)];
    [button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [button setBackgroundImage:[LLTools createImageWithColor:ColorRGB(240, 240, 240)] forState:(UIControlStateSelected)];
    [button setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateSelected)];
}

/** 更改按钮值 */
- (void)ButtonSelect:(UIButton *)button isEnable:(BOOL)isEnable text:(NSString *)text {

    button.userInteractionEnabled = isEnable;
    button.selected = !isEnable;
    [button setTitle:text forState:UIControlStateNormal];
    if (!button.selected) {

        button.layer.cornerRadius = 0;
        button.layer.masksToBounds = NO;

    } else {

        button.layer.cornerRadius = button == _next ? 10.f:15.f;
        button.layer.masksToBounds = YES;
    }
}

/** 场景转换，验证成功之后 */
- (void)Move {

    [_scrollView setContentOffset:CGPointMake(SCREEN_WIDTH, 0) animated:YES];
}

/** 警示语句的展示 */
- (void)textFieldShouldEndEditing:(UITextField *)textField complete:(void (^)(BOOL is))complete {

    [UIView animateWithDuration:0.3 animations:^{
        if (textField.tag == 1100) {
            // 长度警示
            if (textField.text.length < 6 || textField.text.length > 16) {

                _surePasswordTop.constant = _surePasswordTop.constant != 75 ? 75:_surePasswordTop.constant;
                [_surePwdView layoutIfNeeded];
                complete (NO);
            } else {

                _surePasswordTop.constant = _surePasswordTop.constant != 25 ? 25:_surePasswordTop.constant;
                [_surePwdView layoutIfNeeded];
                complete (YES);
            }

        } else {
            // 一致警示
            if (![_password.text isEqualToString:textField.text]) {

                _sureTop.constant = _sureTop.constant != 75 ? 75:_sureTop.constant;
                [_surePwdView layoutIfNeeded];
                complete (NO);
            } else {

                _sureTop.constant =  _sureTop.constant != 25 ? 25:_sureTop.constant;
                [_surePwdView layoutIfNeeded];
                complete (YES);
            }
        }
    }];
}






#pragma mark - 获取短信验证码
- (IBAction)IdentifyingCode:(UIButton *)sender {

    // 限制
    if (_phone.text.length <= 0) {

        [HUD showError:@"请输入手机号码"];
        return;
    }

    if ([LLTools valiMobile:_phone.text]) {

        [HUD showError:@"请输入有效的手机号码"];
        return;
    }

    // 开始获取
    [self ButtonSelect:sender isEnable:NO text:@"正在获取中"];
    NSDictionary *params = @{
                             @"action"  :@"verifycode",
                             @"phone"   :_phone.text
                             };
    [NetManager Get:LLBaseURLTeacher(@"user.do") Auth:NO Params:params Success:^(id Obj) {

        if (Obj) {

            [self ButtonSelect:sender isEnable:YES text:@"获取验证码"];
            [HUD showError:Obj[@"data"][@"msg"]];

        } else {

            // 开启定时器循环输出button的text
            _time = 61;
            _phone.userInteractionEnabled = NO;
            sender.titleLabel.textAlignment = NSTextAlignmentCenter;
            [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(time:) userInfo:nil repeats:YES];
        }

    } Fail:^(NSError *Error) {
        [HUD showError:NetErr];
        [self ButtonSelect:sender isEnable:YES text:@"获取验证码"];

    }];

}

/** 定时器 */
- (void)time:(NSTimer *)timer {

    if (_time <= 0) {

        [timer invalidate];
        timer = nil;
        _phone.userInteractionEnabled = YES;
        [self ButtonSelect:_verificationBtn isEnable:YES text:@"重新发送"];

    } else {

        _time -= 1;
        [_verificationBtn setTitle:[NSString stringWithFormat:@"%ld",_time] forState:UIControlStateNormal];
    }
}

- (void)Pop {

    [self.navigationController popViewControllerAnimated:YES];
}







#pragma mark - 提交验证码
- (IBAction)Sure:(UIButton *)sender {

    if (_verification.text.length <= 0) {
        return;
    }


    [self ButtonSelect:sender isEnable:NO text:@"请稍候..."];
    NSDictionary *params = @{
                             @"action":@"checkPhone",
                             @"phone":_phone.text,
                             @"verifycode":_verification.text
                             };
    // NSString *str = [NSString stringWithFormat:@"%@?action=%@&phone=%@&verifycode=%@",LLBaseURL(@"yxhUser.do"),@"checkPhone",_phone.text,_verification.text];
    [NetManager Post:LLBaseURL(@"yxhUser.do") Auth:NO Params:params Success:^(id Obj) {

        if (![Obj[@"code"] isEqualToNumber:@1000]) {

            [HUD showError:Obj[@"msg"]];
            [self ButtonSelect:sender isEnable:YES text:@"下一步"];
            
        } else {

            _uid = Obj[@"t"][@"uid"];
            [self ButtonSelect:sender isEnable:NO text:@"下一步"];
            [self Move];

        }
    } Fail:^(NSError *Error) {
        
        [HUD showError:NetErr];
        [self ButtonSelect:sender isEnable:YES text:@"下一步"];
    }];
}








#pragma mark - 提交修改
- (IBAction)Commit:(UIButton *)sender {

    // 都匹配时才发起修改请求
    [self textFieldShouldEndEditing:_password complete:^(BOOL first) {

        first == NO ? nil:[self textFieldShouldEndEditing:_surePassword complete:^(BOOL two) {

            if (two) {

                // 修改的请求
                [self ButtonSelect:sender isEnable:NO text:@"请稍候..."];
                NSDictionary *params = @{
                                         @"action":@"setPwd",
                                         @"uid":[_uid stringValue],
                                         @"pwd":_password.text
                                         };
                // NSString *urlStr = [NSString stringWithFormat:@"%@?action=%@&uid=%@&pwd=%@",LLBaseURLTeacher(@"user.do"),@"setPwd",[_uid stringValue],_password.text];
                [NetManager Post:LLBaseURLTeacher(@"user.do") Auth:NO Params:params Success:^(id Obj) {

                    // 说是空值，但Obj还是有值的，只能不做判断了

                        [HUD showSuccess:@"重置密码成功"];
                        [self performSelector:@selector(Pop) withObject:nil afterDelay:1.5];

                } Fail:^(NSError *Error) {

                    [HUD showError:NetErr];
                    [self ButtonSelect:sender isEnable:YES text:@"提交"];
                }];
            }
        }];

    }];

}

@end
